package com.kanshu.ksgb.fastread.doudou.module.book.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.book.fragment.SearchResultFragment;
import com.kanshu.ksgb.fastread.doudou.module.book.view.AdSearchHotAndHistoryLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.view.AdSearchVagueListLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.view.IHotSearchKeyCallback;
import com.kanshu.ksgb.fastread.doudou.module.book.view.IItemClickCallback;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wcy on 2017\7\17 0017
 */

@Route(path = ARouterConfig.SEARCH)
public class SearchActivity extends BaseActivity implements IItemClickCallback, IHotSearchKeyCallback {
    @BindView(R.id.edit_info)
    EditText mEditInfo;
    @BindView(R.id.del)
    ImageView mDel;
    @BindView(R.id.fragment_container)
    FrameLayout mFragmentContainer;
    CallBack mCallBack;
    @BindView(R.id.search_container)
    RelativeLayout mSearchContainer;
    @BindView(R.id.hot_and_history_container)
    AdSearchHotAndHistoryLayout mHotAndHistoryContainer;
    @BindView(R.id.vague_list_container)
    AdSearchVagueListLayout mVagueListContainer;
    boolean mClick;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        goneTitlebar(false);
        setContentView(R.layout.activity_search_layout);
        ButterKnife.bind(this);
        showFragment(SearchResultFragment.newInstance(), "search");
        init();
    }

    private void init() {
        int statusBarHeight = DisplayUtils.getStatusBarHeight(this);
        LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams) mSearchContainer.getLayoutParams();
        lparams.topMargin = statusBarHeight;
        mTitle.setLayoutParams(lparams);
        mEditInfo.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                doSearch();
                return true;
            }
            return false;
        });
        mEditInfo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                handleInput();
            }
        });
        Utils.showSoftKeyboard(mEditInfo, 500);
        mHotAndHistoryContainer.setCallback(this);
        mHotAndHistoryContainer.setHotSearchCallback(this);
        mVagueListContainer.setCallback(this);
        mHotAndHistoryContainer.refresh();
        mEditInfo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("focus", "hasFocus" + hasFocus);
            }
        });
    }

    private void doSearch() {
        String s = mEditInfo.getText().toString();
        if (TextUtils.isEmpty(s.trim())) {
            if (TextUtils.isEmpty(mEditInfo.getHint())) {
                ToastUtil.showMessage(this, "请输入书名");
                return;
            }
            s = mEditInfo.getHint().toString();
        }
        DisplayUtils.visible(mFragmentContainer);
        DisplayUtils.gone(mHotAndHistoryContainer, mVagueListContainer);
        Utils.hideSoftKeyboard(SearchActivity.this);
        mEditInfo.clearFocus();
        if (mCallBack != null) {
            mCallBack.clearInput();
            mCallBack.doSearch(s, null);
        }
        mEditInfo.clearFocus();
        mHotAndHistoryContainer.handleSearchHistory(s);
    }

    private void handleInput() {
        if (mClick) {
            mClick = false;
            return;
        }
        String s = mEditInfo.getText().toString().trim();
        if (TextUtils.isEmpty(s)) {
            mVagueListContainer.refreshByKeyword(s);
            //mEditInfo.clearFocus();
            DisplayUtils.gone(mFragmentContainer, mDel, mVagueListContainer);
            DisplayUtils.visible(mHotAndHistoryContainer);
            if (mCallBack != null) {
                mCallBack.clearInput();
            }
        } else {
            DisplayUtils.visible(mDel, mVagueListContainer);
            DisplayUtils.gone(mHotAndHistoryContainer, mFragmentContainer);
            mVagueListContainer.refreshByKeyword(s);
        }

    }

    public void setCallBack(CallBack callBack) {
        mCallBack = callBack;
    }

    @Override
    public int getContentId() {
        return R.id.fragment_container;
    }

    @OnClick({R.id.search, R.id.left_container, R.id.del})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                doSearch();
                break;
            case R.id.left_container:
                finish();
                break;
            case R.id.del:
                Utils.hideSoftKeyboard(this);
                mEditInfo.setText("");
                //mEditInfo.clearFocus();
                if (mFragmentContainer.getVisibility() == View.VISIBLE) {
                    clearInput();
                }
                DisplayUtils.gone(mFragmentContainer, mVagueListContainer, mDel);
                DisplayUtils.visible(mHotAndHistoryContainer);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClcik(String s, String sub) {
        Utils.hideSoftKeyboard(SearchActivity.this);
        DisplayUtils.visible(mFragmentContainer, mDel);
        DisplayUtils.gone(mHotAndHistoryContainer, mVagueListContainer);
        mClick = true;
        mEditInfo.setText(s);
        mEditInfo.setSelection(s.length());
        mHotAndHistoryContainer.handleSearchHistory(s);
        mCallBack.doSearch(s, sub);
    }

    @Override
    public void onVagueListNoData() {
        DisplayUtils.visible(mFragmentContainer, mDel);
        DisplayUtils.gone(mHotAndHistoryContainer, mVagueListContainer);
        mCallBack.onVagueNoData();
    }

    private void clearInput() {
        String s = mEditInfo.getText().toString().trim();
        if (TextUtils.isEmpty(s)) {
            DisplayUtils.gone(mFragmentContainer, mDel, mVagueListContainer);
            DisplayUtils.visible(mHotAndHistoryContainer);
            if (mCallBack != null) {
                mCallBack.clearInput();
            }
        }
    }

    @Override
    public void onHotSearchKey(@NonNull String key) {
        mEditInfo.setHint(key);
    }

    public interface CallBack {

        void doSearch(String s, String extra);

        void clearInput();

        void onVagueNoData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    public boolean getFragmentContainerVisible(){
        return DisplayUtils.isVisible(mFragmentContainer);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Utils.hideSoftKeyboard(this);
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mEditInfo.getText().toString().length() > 0) {
                mEditInfo.setText("");
                mEditInfo.clearFocus();
                DisplayUtils.gone(mFragmentContainer, mVagueListContainer);
                DisplayUtils.visible(mHotAndHistoryContainer);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
